<template>
   <div class="time-line-root" >
      <spin size="large" fix v-if="loading"></spin>
     <single-timeline ref="single" v-show="view_number==1"
     :lineconfig="lineconfig"></single-timeline>
     <double-timeline ref="double" v-show="view_number==2"
    :lineconfig="lineconfig"></double-timeline>
     <tripple-timeline ref="tripple" v-show="view_number==3"
     :lineconfig="lineconfig"></tripple-timeline>
     <div class="h-view-number-container">
       <div class="h-view-number">View Number</div>
       <div>
         <ButtonGroup class="h-button-group">
           <Button @click="$_changeViewNumber(1)" :type="(view_number==1)?'primary':'ghost'">1</Button>
           <Button  @click="$_changeViewNumber(2)" :type="(view_number==2)?'primary':'ghost'">2</Button>
           <Button  @click="$_changeViewNumber(3)" :type="(view_number==3)?'primary':'ghost'">3</Button>
           <!-- <Button  @click="$_changeViewNumber(6)" :type="(view_number==6)?'primary':'ghost'">6</Button>            -->
         </ButtonGroup>
       </div>
      <div class="h-view-number" style="margin-top:5px;">Channels</div>
     </div>
     <div  class="h-view-number-container h-view-number-container-2">
      <feature-show :feature_data="feature_data">
         <template slot="header">
          <div class="h-view-number">Feature Info</div>
         </template>
      </feature-show>
     </div>
     
  </div> 
</template>

<script>
/*eslint-disable */
import echarts from "echarts";
import _ from "lodash";
import axios from "axios";
import Debug from "debug";

import SingleTimeline from "./SingleViewTimeLine";
import DoubleTimeline from "./DoubleViewTimeLine";
import TrippleTimeline from "./TrippleViewTimeLine";
import FeatureShow from "./FeatureShow/index";

let dbg = Debug("[TimeLine/index]");
dbg.enabled = true;

const channel2danwei = function(channel_raw) {
  let channel = String(channel_raw).toLowerCase();
  if (channel == "speed") {
    return "RPM";
  }
  if (channel.startsWith("i")) {
    return "A";
  }
  if (channel.startsWith("u")) {
    return "V";
  }
  return "";
};

/**
 * @api public
 * @param {Array<{gridIndex:Number,test_id:Number}>} raw_xAxis
 * @param {Array<{gridIndex:Number,test_id:Number,comment:String}>} raw_yAxises
 * @param {Array<{name:String,test_id:Number,xAxisIndex:Number}>} raw_series
 * @param {{chart:Echarts,opt_grids:Array,font_size:Number}} vue
 */
let setup_func = function(raw_xAxis, raw_yAxises, raw_series, vue) {
  dbg("调用setup_func start");
  let opt_grids = vue.opt_grids;
  vue.chart.clear();
  dbg("show loading");
  vue.chart.showLoading();
  let opt_xAxis = raw_xAxis.filter(e => e.gridIndex < opt_grids.length);
  let opt_yAxis = raw_yAxises.filter(e => e.gridIndex < opt_grids.length);
  let opt_series = raw_series.filter(e => e.xAxisIndex < opt_xAxis.length);
  // debugger;
  dbg("opt_series.forEach start");
  opt_series.forEach(e => {
    let yAxisIndex = opt_yAxis.findIndex(yAxis => {
      let testid_equal = e.test_id == yAxis.test_id;
      let name_match = !!($ => {
        let name = e.name;
        if (["speed", "armspeed"].includes(e.name)) {
          return yAxis.comment == "RPM";
        }
        if (["u30", "u45", "u50", "u50e", "u50s", "u50i"].includes(e.name)) {
          return yAxis.comment == "V";
        }
        if (["i30", "i50", "i50e", "i50s"].includes(e.name)) {
          return yAxis.comment == "A";
        }
        if (["p30", "p50", "pp"].includes(e.name)) {
          return yAxis.comment == "W";
        }
      })();
      return testid_equal && name_match;
    });
    if (opt_yAxis[yAxisIndex]) {
      e["yAxisIndex"] = yAxisIndex;
    } else {
      e["yAxisIndex"] = ""; //没找到????
    }
  });
  // debugger;
  opt_series = opt_series.filter(e => !e.name.startsWith("p"));
  opt_series = opt_series.concat(
    [
      {
        name: "Tp"
      },
      {
        name: "Ts"
      },
      {
        name: "To"
      },
      {
        name: "Tw"
      }
    ].map(e => {
      e = {
        ...e,
        xAxisIndex: 0,
        yAxisIndex: 3,
        type: "line",
        data: []
      };
      return e;
    })
  );

  dbg("opt_series.forEach end");
  let opt_legend = (() => {
    return {
      show: true,
      data: _.uniqBy(
        opt_series.map(e => {
          return {
            name: e.name,
            icon: "roundRect"
          };
        }),
        e => e.name
      ),
      // selected:($=>{
      //   let obj= {};
      //   opt_series.map(e=>e.name).forEach(name=>{
      //     if(name.startsWith("T")||name.startsWith("t")){
      //       return obj[name]=false;
      //     }
      //     obj[name] = true;
      //   })
      // })(),
      orient: "vertical",
      right: 85, //85
      top: 80,
      // type: "scroll",
      itemHeight: vue.font_size,
      textStyle: {
        fontSize: vue.font_size,
        rich: {
          small: {
            // color:"red",
            fontSize: vue.font_size - 4,
            lineHeight: vue.font_size,
            padding: [0, 0, 4, 0]
          }
        }
      },
      formatter: function(param) {
        /**@description 从channel名字上消除bosch痕迹
         * @param {String} s
         */
        function PreventBosch(s) {
          if (s.includes("i30") || s.includes("u30") || s.includes("p30")) {
            s = s.replace("30", "s");
          }
          if (s.includes("i45") || s.includes("u45") || s.includes("p45")) {
            s = s.replace("45", "m");
          }
          if (s.includes("i50") || s.includes("u50") || s.includes("p50")) {
            s = s.replace("50", "b");
          }
          if (s == "speed") {
            s = "se";
          }
          return s;
        }
        param = PreventBosch(param);

        param = param.toUpperCase();
        let left = param.substr(1);
        return `${param[0]}{small|${left}}`;
      }
    };
  })();
  dbg("setOption start");
  vue.chart.setOption(
    {
      animation: false,
      backgroundColor: "#FFF",
      tooltip: {
        trigger: "axis",
        textStyle: {
          align: "left"
        },
        axisPointer: {
          type: "cross"
        },
        formatter: params => {
          let res = "&nbsp;&nbsp;&nbsp;time : " + params[0].data[0] + "ms";
          // debugger
          /**@description 从channel名字上消除bosch痕迹
           * @param {String} s
           */
          function PreventBosch(s) {
            s = s.toUpperCase();
            if (s.includes("I30") || s.includes("U30") || s.includes("P30")) {
              s = s.replace("30", "s");
            }
            if (s.includes("I45") || s.includes("U45") || s.includes("P45")) {
              s = s.replace("45", "м");
            }
            if (s.includes("I50") || s.includes("U50") || s.includes("P50")) {
              s = s.replace("50", "в");
            }
            if (s == "SPEED") {
              s = "Se";
            }
            return s;
          }
          params.forEach(v => {
            let series_name = v.seriesName;
            series_name = PreventBosch(series_name);
            res += `<br>${
              v.marker
            } <small color="red">${series_name}</small> : ${v.data[1]} ${channel2danwei(v.seriesName)}`;
          });
          return res;
        }
      },
      grid: vue.opt_grids,
      // dataZoom: [
      //   {
      //     type: "inside",
      //     xAxisIndex: _.range(0, vue.opt_grids.length)
      //   }
      // ],
      yAxis: opt_yAxis,
      xAxis: opt_xAxis,
      legend: opt_legend,
      series: opt_series
    },
    false,
    false
  );
  dbg("setOption end");
  vue.chart.hideLoading();
};

export default {
  data() {
    return {
      sChart: null,
      view_number: 1,
      loading: false,
      // detail_datas: [],
      lineconfig: {
        colors: {
          speed: "#53a6CE",
          i50: "#d5443f",
          i30: "#3332a6",
          u30: "#FA85A7",
          u45: "#51f74a",
          u50: "#d95fee",
          polohousing: "#36AB31",
          solenoidswitch: "#f9683f",
          oil: "#B8B7B2",
          water: "#2E2EF7",
          busbar: "#45f83F"
        },
        line_types: {
          speed: "solid",
          u30: "solid",
          u45: "dashed",
          u50: "dotted",
          i30: "dashed",
          i50: "solid",
          oil: "solid",
          polohousing: "dashed",
          solenoidswitch: "dotted",
          water: "dashed",
          busbar: "dotted"
        }
      },
      max_view_number: 3,
      feature_data: []
    };
  },
  components: {
    SingleTimeline,
    DoubleTimeline,
    TrippleTimeline,
    FeatureShow
  },
  props: {},
  computed: {
    font_size() {
      return 12;
    },
    starterId() {
      return this.$store.state.starterId;
    },
    test_ids() {
      return this.$store.state.testids_for_timeline.slice(
        0,
        this.max_view_number
      );
    }
  },
  methods: {
    $_changeViewNumber(val) {
      this.view_number = val;
    }
  },
  mounted() {},
  watch: {
    test_ids: async function(test_ids) {
      this.loading = true;
      let ps_for_detail = test_ids.map(test_id =>
        axios.get("/starter/detail/", {
          params: {
            starterId: this.starterId,
            testId: test_id
          }
        })
      );
      let all_detail_ps = Promise.all(ps_for_detail);
      let p_for_feature = axios.get("/starter/feature/of_points/", {
        params: {
          starterId: this.starterId,
          test_ids: test_ids
        }
      });
      Promise.all([all_detail_ps, p_for_feature])
        .then($ => (this.loading = false))
        .catch($ => (this.loading = false));
      p_for_feature.then(axresp => {
        this.feature_data = axresp.data;
      });
      all_detail_ps.then(axresps => {
        let detail_datas = axresps.map(axresp => axresp.data);
        // debugger;
        dbg("网络请求数据ok");
        let xAxisData = _.range(0, 3001);
        let opt_xAxis = ($ => {
          return [0, 1, 2].map(($, i) => {
            return {
              type: "category",
              gridIndex: i,
              data: xAxisData,
              axisTick: {
                interval: 499,
                alignWithLabel: true,
                lineStyle: {
                  color: "#333"
                }
              },
              name: test_ids[i] ? `test_id : ${test_ids[i]}` : "",
              test_id: test_ids[i], //DEBUG
              nameGap: 23,
              nameLocation: "center",
              axisLabel: {
                interval: 499
              },
              offset: 5,
              axisLine: {
                onZero: false,
                lineStyle: {}
              }
            };
          });
        })();
        let opt_yAxises = ($ => {
          return _.flatten(
            [0, 1, 2].map(($, i) => {
              return [
                {
                  name: "Voltage /V",
                  type: "value",
                  min: 0,
                  max: 30,
                  offset: 75,
                  position: "right",
                  axisLine: {
                    lineStyle: {
                      color: this.lineconfig.colors["u30"]
                    }
                  },
                  comment: "V" //用于后面找这个轴
                },
                {
                  name: "Speed /RPM",
                  type: "value",
                  min: 0,
                  max: 1500,
                  position: "left",
                  axisLine: {
                    lineStyle: {
                      color: this.lineconfig.colors["speed"]
                    }
                  },
                  comment: "RPM"
                },
                {
                  name: "Current /A",
                  type: "value",
                  min: 0,
                  max: 1500,
                  position: "right",
                  offset: 0,
                  axisLine: {
                    lineStyle: {
                      color: this.lineconfig.colors["i30"]
                    }
                  },
                  comment: "A"
                },
                {
                  name: "POWER /W",
                  type: "value",
                  min: 0,
                  max: 8000,
                  position: "left",
                  offset: 75,
                  axisLine: {
                    lineStyle: {
                      color: this.lineconfig.colors["water"]
                    }
                  },
                  comment: "W"
                }
              ].map(e => {
                e = {
                  ...e,
                  gridIndex: i,
                  splitLine: {
                    show: false
                  },
                  test_id: test_ids[i]
                };
                return e;
              });
            })
          );
        })();
        let opt_serises = ($ => {
          return _.flatten(
            detail_datas.map(({ test_id, channel_data }, i) => {
              let arr = [];
              for (let d of channel_data) {
                let channel_name = d["channel"];
                let data = d["data"];
                arr.push({
                  name: channel_name,
                  xAxisIndex: i,
                  data: data.map((e, i) => [i + 1, e]),
                  // .slice(0,10),
                  lineStyle: {},
                  itemStyle: {},
                  test_id: test_id //debug,and for indexing
                });
              }
              arr.forEach(e => {
                let channel_name = e.name;
                if (this.lineconfig.colors[channel_name]) {
                  e.lineStyle.color = this.lineconfig.colors[channel_name];
                  e.itemStyle.color = this.lineconfig.colors[channel_name];
                }
                e.type = "line";
                e.showSymbol = false;
                e.smooth = true;
                // e.sampling = "max";
              });
              return arr;
            })
          );
        })();
        dbg("计算opt_xAxis,opt_yAxises,opt_serises OK");

        this.$refs["single"]
          ? this.$refs["single"].setOpts(
              opt_xAxis,
              opt_yAxises,
              opt_serises,
              setup_func
            )
          : "";
        this.$refs["double"]
          ? this.$refs["double"].setOpts(
              opt_xAxis,
              opt_yAxises,
              opt_serises,
              setup_func
            )
          : "";
        this.$refs["tripple"]
          ? this.$refs["tripple"].setOpts(
              opt_xAxis,
              opt_yAxises,
              opt_serises,
              setup_func
            )
          : "";
      });
    },
    starterId() {
      this.feature_data = [];
    }
  }
};
</script>

<style lang="scss">
.time-line-root {
  width: 1526px;
  height: 712px;
  overflow-y: auto;
  // overflow-x: hidden;
  .h-view-number-container {
    $gray: #b5b5b5;
    $hwidth: 98px;
    position: absolute;
    top: 0;
    right: 0;
    width: 214px;
    padding-left: 70px;
    &.h-view-number-container-2 {
      top: 300px;
    }
    .h-view-number {
      margin-bottom: 5px;
      width: $hwidth;
      margin-bottom: 8px;
      font-size: 12px;
      display: inline-block;
      border-bottom: solid 1px $gray;
    }
    .h-button-group {
      &.ivu-btn-group {
        .ivu-btn {
          padding: 0px 6px;
          &:not(:first-child) {
            margin-left: 5px;
          }
        }
        .ivu-btn-primary {
          background-color: $gray;
          border-color: $gray;
          &:focus {
            box-shadow: 0 0 0 0px $gray;
          }
        }
        .ivu-btn-ghost {
          color: $gray;
        }
        .ivu-btn-ghost:focus {
          box-shadow: 0 0 0 0px $gray;
        }
        .ivu-btn-ghost:hover {
          color: $gray;
          border-color: $gray;
        }
        .ivu-btn-primary ~ .ivu-btn {
          border-color: $gray;
        }
      }
    }
  }
}
</style>
